package com.bc.upgrade.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bc.upgrade.utils.BeanFactory;
import com.bc.upgrade.utils.BsdiffUtil;
import com.bc.upgrade.utils.CommonUtil;




/**
 * 返回给客户端patch差异包的URL地址
 * 思路:
 *		1.检查客户端传来的版本号是否和服务器中的apk版本号一致
 *		2.一致返回0,不一致返回1
 *		3.如果返回值为1,检查服务器中是否有客户端对应的最新差异包
 *		4.有最新差异包,返回给客户端url地址,让其下载
 *		5.没有差异包,调用差异包分解程序,生成最新差异包,返回给客户端Url地址,让其下载
 * @author duguang
 * @date 2013.12.29
 * @version 1.0
 * @boke http://blog.csdn.net/duguang77
 *
 */
public class UpGradeServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		String jsonStr = request.getParameter("body");
		System.out.println(jsonStr);
		if(jsonStr!=null){
			String versionCode = BeanFactory.getVersionCode();
			if(jsonStr!=versionCode){//版本不一样,生成差异包的Url地址
				
				//获取旧版本号名称
				String oldApk = BeanFactory.getVersionName(jsonStr);
				
				//获取新版本号名称
				String newApk = BeanFactory.getVersionName(versionCode);
				
				//获取差异包的Url地址
				String patchUrl = BsdiffUtil.getPatchUrl(oldApk, newApk);
				
				CommonUtil.renderText(response, patchUrl);
			}else{
				CommonUtil.renderText(response, null);
			}
		}
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
